package cn.spring.ly.controller.advice;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.alibaba.fastjson.JSON;

import cn.spring.ly.result.AjaxResult;

@ControllerAdvice
public class AuthorizationAdvice {

	/**
	 * 没有权限异常处理
	 * @param e
	 * @param req
	 * @param resp
	 * @return
	 */
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	@ExceptionHandler(UnauthorizedException.class)
	public String ajaxunauthed(UnauthorizedException e,HttpServletRequest req,HttpServletResponse resp){
		
        if(!StringUtils.isEmpty(req.getHeader("x-requested-with")) && req.getHeader("x-requested-with").equals("XMLHttpRequest")){  
        	try {
        		req.setCharacterEncoding("utf-8");
        		resp.setCharacterEncoding("utf-8");
        		resp.setContentType("text/html;charset=utf-8");
				resp.getWriter().print(JSON.toJSONString(AjaxResult.error("没有权限访问")));
				return null;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
        } 

		return "403_unauth";
	}
}
